package com.lyk.coursearrange.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyk.coursearrange.common.core.base.result.R;
import com.lyk.coursearrange.common.log.annotation.Log;
import com.lyk.coursearrange.common.log.enums.OperationType;
import com.lyk.coursearrange.common.utils.StringUtils;
import com.lyk.coursearrange.dao.SourcePeopleDao;
import com.lyk.coursearrange.entity.CustomerInformation;
import com.lyk.coursearrange.entity.Stages;
import com.lyk.coursearrange.entity.Student;
import com.lyk.coursearrange.entity.TeachStuInfo;
import com.lyk.coursearrange.service.*;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("teachStuInfo")
@RequiredArgsConstructor
public class TeachStuInfoController {

    private final StudentService studentService;
    private final TeachStuInfoService teachStuInfoService;
    private final SourcePeopleDao sourcePeopleDao;
    private final TeacherService teacherService;
    private final OnlineCategoryService onlineCategoryService;
    private final CustomerInformationService customerInformationService;


    @GetMapping("customerInformationList")
    @Log(title = "其他", operationType = OperationType.SELECT)
    public R<PageInfo<CustomerInformation>> customerInformationList(CustomerInformation customerInformation,
                                                                    @RequestParam(defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);

        LambdaQueryWrapper<CustomerInformation> wrapper = new LambdaQueryWrapper<CustomerInformation>()
                .eq(CustomerInformation::getType, 2);

        List<CustomerInformation> lists = customerInformationService.list(wrapper);
        for (CustomerInformation list : lists) {
            list.setStages(sourcePeopleDao.selectstages(list.getCustomerId()));
        }

        PageInfo<CustomerInformation> pageInfo = new PageInfo<>(lists);
        return R.ok().data("list", pageInfo);
    }

    @GetMapping("list")
    @Log(title = "其他", operationType = OperationType.SELECT)
    public R<PageInfo<TeachStuInfo>> list(TeachStuInfo teachStuInfo,
                                          @RequestParam(defaultValue = "1") Integer pageNo,
                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);

        List<TeachStuInfo> lists = teachStuInfoService.lists(teachStuInfo);
        for (TeachStuInfo list : lists) {
            list.setStages(sourcePeopleDao.selectstages(list.getCustomerInformationId()));
        }

        PageInfo<TeachStuInfo> pageInfo = new PageInfo<>(lists);
        return R.ok().data("list", pageInfo);
    }

    @GetMapping("getById/{id}")
    @Log(title = "其他", operationType = OperationType.SELECT)
    public R<TeachStuInfo> getById(@PathVariable("id") String id) {

        TeachStuInfo byId = teachStuInfoService.getById(id);
        if (byId == null) {
            return R.error("没有此成单客资");
        }
        CustomerInformation customerInformation = customerInformationService.getById(byId.getCustomerInformationId());
        if (customerInformation == null) {
            return R.error("没有此成单客资");
        }

        List<Stages> selectStages = sourcePeopleDao.selectstages(customerInformation.getCustomerId());
        if (selectStages.size() > 0) {
            if (byId.getIsAllPay().equals(1)) {
                byId.setStages(selectStages);
            }
        }

        return R.ok().data("list", byId);
    }


    @PostMapping("save")
    @Transactional
    @Log(title = "其他", operationType = OperationType.SELECT)
    public R<TeachStuInfo> save(@Validated @RequestBody TeachStuInfo teachStuInfo) {
        if (teachStuInfo.getCustomerInformationId() == null) {
            return R.error("客资id不能为空");
        }

        TeachStuInfo one = teachStuInfoService.getOne(
                new LambdaQueryWrapper<TeachStuInfo>()
                        .eq(TeachStuInfo::getCustomerInformationId, teachStuInfo.getCustomerInformationId())
        );
        if (one != null) {
            return R.error("该客资已提交");
        }

        // 交了诊断费
        if (teachStuInfo.getIsDiagnosisAllPay().equals(2)) {
            if (teachStuInfo.getDiagnosisAllPayMoney() == null) {
                return R.error("诊断费金额不能为空");
            }
            if (teachStuInfo.getDiagnosisTime() == null) {
                return R.error("诊断时间不能为空");
            }
            if (teachStuInfo.getDiagnosisPayType() == null) {
                return R.error("诊断类型不能为空");
            }
        }

        // 尾款分期
        if (teachStuInfo.getIsAllPay().equals(2)) {
            for (Stages stage : teachStuInfo.getStages()) {
                if (StringUtils.isEmpty(stage.getStagesDate()) || stage.getPayType() == null || StringUtils.isEmpty(stage.getStagesMoney())) {
                    return R.error("表格不完善");
                }
            }
            teachStuInfo.setDiagnosisAllPayMoney(null);
            isAllPay(teachStuInfo);
        } else {
            //全款
            if (teachStuInfo.getAllPayMoney() == null) {
                return R.error("金额不能为空");
            }
            if (teachStuInfo.getPayTime() == null) {
                return R.error("全款时间不能为空");
            }
            if (teachStuInfo.getPayType() == null) {
                return R.error("类型不能为空");
            }
        }

//        Student student = Student.builder()
//                .studentNo(System.currentTimeMillis() + " ")
//                .password("123456")
//                .username(teachStuInfo.getStudentName())
//                .realname(teachStuInfo.getStudentName())
//                .userType(3)
//                .address(teachStuInfo.getAddress())
//                .sex(String.valueOf(teachStuInfo.getSex()))
//                .grade(teachStuInfo.getGrade()[1]).build();
//        studentService.save(student);

        teachStuInfo.setCategoryId(teachStuInfo.getCourseCategoryId()[1]);
//        teachStuInfo.setStudentId(student.getId());
        teachStuInfo.setCreateTime(new Date());
        teachStuInfo.setIsUpdate(1);
        teachStuInfoService.save(teachStuInfo);

        CustomerInformation customerInformation = new CustomerInformation();
        customerInformation.setCustomerId(teachStuInfo.getCustomerInformationId());
        customerInformation.setCustomerStudent(teachStuInfo.getStudentName());
        customerInformationService.updateById(customerInformation);

        customerInformationService.update(
                new LambdaUpdateWrapper<CustomerInformation>()
                        .set(CustomerInformation::getType, 2)
                        .eq(CustomerInformation::getCustomerId, teachStuInfo.getCustomerInformationId())
        );

        return R.ok();

    }


    @PutMapping("update")
    @Transactional
    @Log(title = "其他", operationType = OperationType.SELECT)
    public R<TeachStuInfo> update(@Validated @RequestBody TeachStuInfo teachStuInfo) {
        teachStuInfo.setCategoryId(teachStuInfo.getCourseCategoryId()[1]);
        if (teachStuInfo.getId() == null) {
            return R.error("id不能为空");
        }
        TeachStuInfo stuInfoVTO = teachStuInfoService.getById(teachStuInfo.getId());
        if (stuInfoVTO == null) {
            return R.error("没有此成单");
        }
        if (stuInfoVTO.getIsUpdate().equals(2)) {
            return R.error("该成单已经修改过");
        }
        if (teacherService.getById(stuInfoVTO.getTeacherId()) == null) {
            return R.error("没有此老师");
        }
        if (onlineCategoryService.getById(stuInfoVTO.getCategoryId()) == null) {
            return R.error("没有此课程");
        }

        //交了诊断费
        if (teachStuInfo.getIsDiagnosisAllPay().equals(2)) {
            if (teachStuInfo.getDiagnosisAllPayMoney() == null) {
                return R.error("诊断费金额不能为空");
            }
            if (teachStuInfo.getDiagnosisTime() == null) {
                return R.error("诊断时间不能为空");
            }
            if (teachStuInfo.getDiagnosisPayType() == null) {
                return R.error("诊断类型不能为空");
            }
        } else {
            teachStuInfo.setDiagnosisAllPayMoney(null);
            teachStuInfo.setDiagnosisTime(null);
            teachStuInfo.setDiagnosisPayType(null);
        }

        //分期
        if (teachStuInfo.getIsAllPay().equals(2)) {
            for (Stages stage : teachStuInfo.getStages()) {
                if (StringUtils.isEmpty(stage.getStagesDate()) || stage.getPayType() == null || StringUtils.isEmpty(stage.getStagesMoney())) {
                    return R.error("表格不完善");
                }
            }
            teachStuInfo.setAllPayMoney(null);
            teachStuInfo.setPayTime(null);
            teachStuInfo.setPayType(null);
            teachStuInfo.setDiagnosisAllPayMoney(new BigDecimal(0));
            sourcePeopleDao.deletebycustomeridone(teachStuInfo.getCustomerInformationId());
            sourcePeopleDao.deletebycustomeridtwo(teachStuInfo.getCustomerInformationId());
            isAllPay(teachStuInfo);
        } else {
            //全款
            if (teachStuInfo.getAllPayMoney() == null) {
                return R.error("金额不能为空");
            }
            if (teachStuInfo.getPayTime() == null) {
                return R.error("全款时间不能为空");
            }
            if (teachStuInfo.getPayType() == null) {
                return R.error("类型不能为空");
            }
        }

//        Student student = Student.builder()
//                .id(stuInfoVTO.getStudentId())
//                .username(teachStuInfo.getStudentName())
//                .realname(teachStuInfo.getStudentName())
//                .address(teachStuInfo.getAddress())
//                .sex(String.valueOf(teachStuInfo.getSex()))
//                .grade(teachStuInfo.getGrade()[1]).build();
//        studentService.updateById(student);

        CustomerInformation customerInformation = new CustomerInformation();
        customerInformation.setCustomerId(teachStuInfo.getCustomerInformationId());
        customerInformation.setCustomerStudent(teachStuInfo.getStudentName());
        customerInformationService.updateById(customerInformation);

        teachStuInfo.setCustomerInformationId(stuInfoVTO.getCustomerInformationId());
        teachStuInfo.setCategoryId(teachStuInfo.getCourseCategoryId()[1]);
        teachStuInfo.setIsUpdate(2);
        teachStuInfoService.updateById(teachStuInfo);

        return R.ok();

    }


    public void isAllPay(TeachStuInfo teachStuInfo) {
        // 分期
        if (teachStuInfo.getIsAllPay() == 2) {
            for (Stages stage : teachStuInfo.getStages()) {
                sourcePeopleDao.insertstages(stage);
                sourcePeopleDao.insertcustomerasstages(teachStuInfo.getCustomerInformationId(), stage.getStagesId());
            }
        } else {
            sourcePeopleDao.deletebycustomeridone(teachStuInfo.getCustomerInformationId());
            sourcePeopleDao.deletebycustomeridtwo(teachStuInfo.getCustomerInformationId());
        }
    }


}
